import handlebars from 'handlebars'
import inquirer from 'inquirer'
import fs from 'fs'
import * as prettier from 'prettier'
import path from 'path'

// 一段交互提示
const KYES = {
  question1: '创建组件还是界面',
  question2: '输入组件名，开头必须大写',
  question3: '输入输出路径（基于src里边）',
  question4: '输入页面名，开头必须大写',
  question5:
    '输入页面路径，主包必须是pages,子包必须以pages-开头（基于src文件夹）',
}
const questionList1 = ['组件', '页面', '取消']
// prettier格式化操作
const jsonFormatConfig = {
  parser: 'json',
  semi: false,
  tabWidth: 2,
  singleQuote: true,
  endOfLine: 'auto',
}
// 递归创建文件夹
const mkdirsSync = (dirname) => {
  if (fs.existsSync(dirname)) return true
  if (mkdirsSync(path.dirname(dirname))) {
    fs.mkdirSync(dirname)
    return true
  }
}

// 创建组件
const makeComponent = (name, url) => {
  const filePath = path.resolve('./template/assets/component.tpl')
  const data = fs.readFileSync(filePath, 'utf-8')
  const componentsName = 'Panel' + name
  const targetFilePath = path.join(`./src/${url}`)
  const targetPath = path.join(targetFilePath, `/${componentsName}.vue`)

  if (fs.existsSync(targetPath)) {
    throw new Error('目标文件已存在该文件，请确认后重新选择')
  }

  if (!fs.existsSync(targetFilePath)) {
    mkdirsSync(targetFilePath) // 创建文件夹
  }

  const str = handlebars.compile(data)({
    moduleName: name,
  })
  fs.writeFile(targetPath, str, 'utf-8', () => {})
  console.log('组件创建成功!!')
}

// 创建界面 name 和 路径
const makePage = async (name, url) => {
  const pagesPath = path.resolve('./src/pages.json')
  const pagesData = fs.readFileSync(pagesPath, 'utf-8')
  const templatePath = path.resolve('./template/assets/page.tpl')
  const templateData = fs.readFileSync(templatePath, 'utf-8')
  const targetFilePath = path.join(`./src/${url}`)
  const targetPath = path.join(targetFilePath, `/index.vue`)
  const pagesJsonFormate = pagesData.replace(/\/\/.*\n/g, '') // 剔除可能出现的备注
  const parsePagesJson = JSON.parse(pagesJsonFormate)

  if (fs.existsSync(targetPath)) {
    throw new Error('目标文件已存在该文件，请确认后重新选择')
  }

  if (!fs.existsSync(targetFilePath)) {
    mkdirsSync(targetFilePath) // 创建文件夹
  }

  // 解析下url是主包还是子包
  const isSubPage = (url) => url !== 'pages' && url.indexOf('-') > -1

  if (isSubPage(url)) {
    // 往pagesjson写入子包配置
    const parseUrl = url.split('/')
    const firstSubName = parseUrl[0]
    const subPath = (() => url.replace(firstSubName + '/', '') + '/index')()
    const { subPackages = [] } = parsePagesJson
    if (!subPackages.find((v) => v.root === firstSubName)) {
      subPackages.push({
        root: firstSubName,
        pages: [],
      })
    }
    const rootIndex = subPackages.findIndex((v) => v.root === firstSubName)
    const rootItem = subPackages[rootIndex]
    const rootPages = rootItem.pages
    if (!rootPages.find((v) => v.path === subPath)) {
      rootPages.push({
        path: subPath,
      })
    }
    parsePagesJson.subPackages = subPackages
    let pagesStr = ''
    try {
      pagesStr = await prettier.format(
        JSON.stringify(parsePagesJson),
        jsonFormatConfig,
      )
    } catch (error) {}
    fs.writeFile(pagesPath, pagesStr, 'utf-8', () => {}) // 文件夹下创建页面组件
  } else {
    // 主包逻辑
    const { pages } = parsePagesJson
    const item = pages.find((v) => v.path === url + '/index')
    if (item) {
      throw new Error('页面文件已存在，请核对下名称')
    }
    pages.push({
      path: url + '/index',
      style: {},
    })
    parsePagesJson.pages = pages
    let pagesStr = ''
    try {
      pagesStr = await prettier.format(
        JSON.stringify(parsePagesJson),
        jsonFormatConfig,
      )
    } catch (error) {}
    fs.writeFile(pagesPath, pagesStr, 'utf-8', () => {}) // 文件夹下创建页面组件
  }

  const str = handlebars.compile(templateData)({
    moduleName: name,
  })
  fs.writeFile(targetPath, str, 'utf-8', (err) => {
    if (err) {
      return
    }

    console.log('页面创建成功!!')
  }) // 文件夹下创建页面组件
}

;(async () => {
  // 1 选择创建类型
  const res = await inquirer.prompt([
    {
      type: 'list',
      name: KYES.question1,
      choices: questionList1,
    },
  ])
  if (res[KYES.question1] === questionList1[2]) return // 取消
  // 选择组件
  if (res[KYES.question1] === questionList1[0]) {
    const input = await inquirer.prompt([
      {
        type: 'input',
        name: KYES.question2,
        default: '',
      },
      {
        type: 'input',
        name: KYES.question3,
        default: '',
      },
    ])
    if (input[KYES.question2] && input[KYES.question3]) {
      makeComponent(input[KYES.question2], input[KYES.question3])
    }
  }

  // 选择页面
  if (res[KYES.question1] === questionList1[1]) {
    const input = await inquirer.prompt([
      {
        type: 'input',
        name: KYES.question4,
        default: '',
      },
      {
        type: 'input',
        name: KYES.question5,
        default: '',
      },
    ])
    if (input[KYES.question4] && input[KYES.question5]) {
      makePage(input[KYES.question4], input[KYES.question5])
    }
  }
})()
